<template>
  <div>
    <el-tree :data="categoryData" :props="defaultProps" default-expand-all>
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <div>
            <el-image :src="data.picUrl" v-if="data.level==2" />
            <span>
              <span>{{node.label}}</span>
              <el-tag
                style="margin-left:10px"
                :type="data.level==0?'danger':data.level==1?'warning':'success'"
                v-if="data.title!='全部类目'"
              >{{grade(data.level)}}</el-tag>
            </span>
          </div>
          <div>
            <el-button
              type="primary"
              size="small"
              round
              @click.stop="addCategory(node.data.id)"
              v-if="data.level!=2"
            >添加</el-button>
            <el-button
              type="warning"
              size="small"
              round
              @click.stop="amendCategory(data)"
              v-if="data.title!='全部类目'"
            >编辑</el-button>
            <el-button
              type="danger"
              size="small"
              round
              @click.stop="deleteCategory(node.data.id)"
              v-if="data.firstLevelId&&!data.childrenList"
            >删除</el-button>
          </div>
        </div>
      </template>
    </el-tree>
    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="类目名称" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入类目名称" />
        </el-form-item>
        <el-form-item label="类目图片" prop="picUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            action="http://192.168.1.188:8080/upload/admin"
            :on-success="handleAvatarSuccess"
            :headers="token"
          >
            <span>
              <el-image :src="ruleForm.picUrl" />
            </span>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="title=='创建'?confirmAdd('ruleFormRef'):confirmCompile('ruleFormRef')"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {post,get} from "@/utlis/http";
import Cookies from "js-cookie";
export default {
  data() {
    return {
      categoryData: [], //类目数据
      defaultProps: {
        children: "childrenList",
        label: "title",
      },
      dialogVisible: false, //对话框
      title: "创建",
      ruleForm: {
        title: "", //类目标题
        id: "", //类目ID
        parentId: "", //类目父节点
        picUrl: "", //类目图片
      },
      rules: {
        // 添加表单验证
        title: [{ required: true, message: "请输入类目标题", trigger: "blur" }],
      },
    };
  },
  computed: {
    token() {
      let headers = { AdminToken: Cookies.get("token") };
      return headers;
    },
    //等级
    grade() {
      return (level) => {
        if (0 == level) {
          return "一级";
        } else if (1 == level) {
          return "二级";
        } else {
          return "三级";
        }
      };
    },
  },
  created() {
    this.initialize();
  },
  methods: {
    //初始化类目数据
    initialize() {
      let data = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      get(data).then((res) => {
        let { data, errno } = res.data;
        if (200 == errno) {
          this.categoryData = [
            {
              parentId: 0,
              title: "全部类目",
              childrenList: data,
            },
          ];
        }
      });
    },
    //上传图片
    handleAvatarSuccess(res, file) {
      let { errno, url } = res;
      if (200 == errno) {
        this.ruleForm.picUrl = url;
      } else {
        ElMessage.warning("图片上传失败");
      }
    },
    // 添加
    addCategory(id) {
      this.ruleForm.parentId = id;
      this.title = "创建";
      this.ruleForm.title = "";
      this.ruleForm.picUrl = "";
      this.dialogVisible = true;
    },
    //保存添加
    confirmAdd(ruleFormRef) {
      this.$refs[ruleFormRef].validate((valid) => {
        if (valid == false) {
          return;
        } else {
          let data = {
            _gp: "admin.category",
            _mt: "create",
            ...this.ruleForm,
          };
          post(data).then((res) => {
            let { errno, errmsg } = res.data;
            if (200 == errno) {
              this.initialize();
              ElMessage.success("添加成功");
              this.dialogVisible = false;
            } else {
              ElMessage.warning(errmsg);
            }
          });
        }
      });
    },
    //编辑
    amendCategory(data) {
      this.title = "编辑";
      this.dialogVisible = true;
      Object.assign(this.ruleForm, data);
    },
    //保存编辑
    confirmCompile(ruleFormRef) {
      this.$refs[ruleFormRef].validate((valid) => {
        if (valid == false) {
          return;
        } else {
          let data = {
            _gp: "admin.category",
            _mt: "update",
            ...this.ruleForm,
          };
          post(data).then((res) => {
            let { errno, errmsg } = res.data;
            if (200 == errno) {
              this.dialogVisible = false;
              this.initialize();
              ElMessage.success("编辑成功");
            } else {
              ElMessage.warning(errmsg);
            }
          });
        }
      });
    },
    //删除
    deleteCategory(id) {
      ElMessageBox.confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            _gp: "admin.category",
            _mt: "delete",
            id: id,
          };
          post(data).then((res) => {
            if (200 == res.data.errno) {
              this.initialize();
              ElMessage.success("删除成功");
            }
          });
        })
        .catch(() => {
          ElMessage.info("取消删除");
        });
    },
    //关闭对话框
    handleClose() {
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 15px;
  padding-right: 8px;
  .el-image {
    width: 20px;
    vertical-align: middle;
    margin-right: 10px;
  }
}
/deep/ .el-tree-node__content {
  height: 50px;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader /deep/ .el-upload {
  width: 100%;
  height: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader /deep/ .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>
